package com.shuoyue.ycgk.ui.questionbank.base;

import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.viewpager.widget.ViewPager;

import com.shuoyue.ycgk.Constant;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.base.BaseMvpFragment;
import com.shuoyue.ycgk.entity.Option;
import com.shuoyue.ycgk.entity.QuestionParent;
import com.shuoyue.ycgk.entity.QuestionSimple;
import com.shuoyue.ycgk.entity.UserAnswer;
import com.shuoyue.ycgk.entity.UserAnswerPager;
import com.shuoyue.ycgk.net.exception.NetErrorException;
import com.shuoyue.ycgk.ui.common.CstWebActivity;
import com.shuoyue.ycgk.ui.questionbank.practice.mok.MokQuestionMateralFragment;
import com.shuoyue.ycgk.ui.questionbank.reportwrong.ReportWrongQuestionActivity;
import com.shuoyue.ycgk.views.PaintView;
import com.shuoyue.ycgk.views.dialog.SimpleProgressDialog;
import com.shuoyue.ycgk.views.dialog.TextSizeDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public abstract class BaseQuestionActivity<T extends BaseMateriFragment, K extends BaseSimpleFragment>
        extends BaseMvpActivity {

    @BindView(R.id.viewPager)
    public ViewPager viewPager;
    @BindView(R.id.name)
    public TextView name;
    @BindView(R.id.back)
    public ImageView back;
    @BindView(R.id.paper)
    public ImageView paper;
    @BindView(R.id.card)
    public ImageView card;
    @BindView(R.id.time)
    public TextView time;
    @BindView(R.id.set)
    public ImageView set;
    @BindView(R.id.paint_view)
    PaintView paintView;
    @BindView(R.id.lay_paint_controll)
    LinearLayout layPaintControll;

    public List<QuestionParent> questionParents;
    public BaseMateriAdapter<T, K> questionFragmentAdapter;
    public int total;


    public QuestionSimple currentSimple;

    public abstract Class<T> getClassT();

    public abstract Class<K> getClassK();

    TextSizeDialog dialog;

    protected SimpleProgressDialog spotsDialog2;

    HashMap<Integer, ArrayList<PaintView.DrawPath>> notepad = new HashMap();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_question_item;
    }

    @Override
    protected void initView() {
        showLoadingSimple();
        paintView.setChangeCallback(mPathList -> {
            if (currentSimple != null) {
                if (notepad.get(currentSimple.getQuestionId()) != null) {
                    notepad.get(currentSimple.getQuestionId()).clear();
                    notepad.get(currentSimple.getQuestionId()).addAll(mPathList);
                } else {
                    ArrayList<PaintView.DrawPath> drawPaths = new ArrayList<>();
                    drawPaths.addAll(mPathList);
                    notepad.put(currentSimple.getQuestionId(), drawPaths);
                }
            }
        });
    }

    void showLoadingSimple() {
        if (spotsDialog2 == null) {
            spotsDialog2 = new SimpleProgressDialog(mContext, "深呼吸~来刷题");
        }
        spotsDialog2.show();
    }

    @Override
    public void initData() {
    }


    /**
     * 跳转下一题
     */
    public void goNext() {
        if (viewPager.getCurrentItem() == questionFragmentAdapter.getCount() - 1) {
            //最后一个
            lastOne();
        } else {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
        }
    }


    @OnClick({R.id.back, R.id.paper, R.id.set, R.id.card, R.id.time, R.id.close, R.id.last, R.id.clear, R.id.next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                if (paintView.getVisibility() == View.VISIBLE) {
                    paintView.setVisibility(View.GONE);
                } else {
                    back();
                }

                break;
            case R.id.paper:
                if (paintView.getVisibility() == View.VISIBLE) {
                    paintView.setVisibility(View.GONE);
                    layPaintControll.setVisibility(View.GONE);

                } else if (questionParents != null
                        && questionParents.size() > 0
                        && currentSimple != null) {
//                    paintView.removeAllPaint();
                    if (notepad.get(currentSimple.getQuestionId()) != null) {
                        paintView.drawNewPaint(notepad.get(currentSimple.getQuestionId()));
                    }
                    layPaintControll.setVisibility(View.VISIBLE);
                    paintView.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.set:
                if (dialog == null) {
                    dialog = new TextSizeDialog(mContext);
                }
                dialog.setCallback(new TextSizeDialog.Onclick() {

                    @Override
                    public void wrong() {
                        ReportWrongQuestionActivity.start(mContext, 1, currentSimple.getQuestionId());
//                        CstWebActivity.start(mContext, Constant.serviceUrl, "错题反馈");
                    }

                    @Override
                    public void textf(int textSize) {
                        for (QuestionParent questionParent : questionParents) {
                            questionParent.setTextSize(textSize);
                            if (questionParent.getQuestionSimpleDTOS() != null)
                                for (QuestionSimple itme :
                                        questionParent.getQuestionSimpleDTOS()) {
                                    itme.setTextsize(textSize);
                                }
                        }
//                        questionFragmentAdapter.notifyDataSetChanged();
//                        changeTextSize();
                        resetTextSize();
                    }

                });
                dialog.show();
                break;
            case R.id.card:
                showAnswerCard();
                break;
            case R.id.time:
                break;

            case R.id.close:
                paintView.setVisibility(View.GONE);
                layPaintControll.setVisibility(View.GONE);
                break;
            case R.id.last:
                paintView.undo();
                break;
            case R.id.clear:
                paintView.removeAllPaint();
                break;
            case R.id.next:
                paintView.redo();
                break;
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (questionFragmentAdapter != null) {
            BaseMvpFragment fragment = questionFragmentAdapter.getCurrentFragment();
            if (fragment instanceof BaseMateriFragment) {
                ((T) fragment).gesture.onTouchEvent(event);
            }
        }
        super.dispatchTouchEvent(event);
        return false;
    }

    public void setThisActData(List<QuestionParent> questionParentList, boolean isShowRight) {
        this.questionParents = questionParentList;
        encode(questionParents, isShowRight);
        questionFragmentAdapter = new BaseMateriAdapter<T, K>(getSupportFragmentManager(),
                questionParents, total, getClassT(), getClassK());
        viewPager.setAdapter(questionFragmentAdapter);
    }

    public void setThisActData(List<QuestionParent> questionParentList) {
        setThisActData(questionParentList, true);
    }

    public void setCheckData(List<QuestionParent> questionParentList) {
        this.questionParents = questionParentList;
        encodeCheck(questionParents);
        questionFragmentAdapter = new BaseMateriAdapter<T, K>(getSupportFragmentManager(),
                questionParents, total, getClassT(), getClassK());
        viewPager.setAdapter(questionFragmentAdapter);
        if (spotsDialog2 != null) {
            spotsDialog2.cancel();
        }
    }

    public abstract void lastOne();

    public abstract void back();


    public void encode(List<QuestionParent> questionParents, boolean isShowRight) {
        if (questionParents == null) {
            if (spotsDialog2 != null) {
                spotsDialog2.cancel();
            }
            return;
        }

        int now = 1;
        for (int i = 0; i < questionParents.size(); i++) {
            QuestionParent questionParent = questionParents.get(i);
            //跳过过渡页
            if (questionParent.isSpcePage()) {
                continue;
            }

            if (questionParent.getIsMaterial() == 1) {
                //材料题,编号
                for (QuestionSimple questionSimple : questionParent.getQuestionSimpleDTOS()) {
                    questionSimple.setParentPos(i);
                    questionSimple.setNum(now);
                    now++;
                    swipMyAnswer(questionSimple, isShowRight);
                    //设置选项是否正确
                    if (questionSimple.getQuestionSimpleOptionDTOS() != null)
                        for (Option o : questionSimple.getQuestionSimpleOptionDTOS()) {
                            if (questionSimple.getRightKey().contains(o.getNo())) {
                                o.setRight(true);
                            }
                        }
                    //判断题需要自己加选项
                    if (questionSimple.getQuestionType() == 3) {
                        questionSimple.setRightKey("1".equals(questionSimple.getRightKey())
                                ? "A" : "B");
                        if (questionSimple.getAnswer() != null && questionSimple.getAnswer().equals("1")) {
                            questionSimple.setAnswer("A");
                        } else if (questionSimple.getAnswer() != null && questionSimple.getAnswer().equals("2")) {
                            questionSimple.setAnswer("B");
                        }
                        ArrayList<Option> options = new ArrayList<>();
                        Option option1 = new Option("A", "正确", "A".equals(questionSimple.getRightKey()), !TextUtils.isEmpty(questionSimple.getAnswer()) &&
                                questionSimple.getAnswer().equals("A"));
                        Option option2 = new Option("B", "错误", "B".equals(questionSimple.getRightKey()), !TextUtils.isEmpty(questionSimple.getAnswer()) &&
                                questionSimple.getAnswer().equals("B"));
                        options.add(option1);
                        options.add(option2);
                        questionSimple.setQuestionSimpleOptionDTOS(options);
                    }
                }
            } else {
                QuestionSimple questionSimple = questionParent.getQuestionSimpleDTOS().get(0);
                questionSimple.setParentPos(i);
                questionSimple.setNum(now);
                now++;


                //设置选项是否正确
                if (questionSimple.getQuestionSimpleOptionDTOS() != null)
                    for (Option o : questionSimple.getQuestionSimpleOptionDTOS()) {
                        if (questionSimple.getRightKey().contains(o.getNo())) {
                            o.setRight(true);
                        }
                        if (questionSimple.getAnswer() != null &&
                                questionSimple.getAnswer().contains(o.getNo())) {
                            o.setSelect(true);
                        }
                    }

                //判断题需要自己加选项
                if (questionSimple.getQuestionType() == 3) {
                    questionSimple.setRightKey("1".equals(questionSimple.getRightKey())
                            ? "A" : "B");
                    if (questionSimple.getAnswer() != null && questionSimple.getAnswer().equals("1")) {
                        questionSimple.setAnswer("A");
                    } else if (questionSimple.getAnswer() != null && questionSimple.getAnswer().equals("2")) {
                        questionSimple.setAnswer("B");
                    }

                    ArrayList<Option> options = new ArrayList<>();
                    Option option1 = new Option("A", "正确", "A".equals(questionSimple.getRightKey()), !TextUtils.isEmpty(questionSimple.getAnswer()) &&
                            questionSimple.getAnswer().equals("A"));
                    Option option2 = new Option("B", "错误", "B".equals(questionSimple.getRightKey()), !TextUtils.isEmpty(questionSimple.getAnswer()) &&
                            questionSimple.getAnswer().equals("B"));
                    options.add(option1);
                    options.add(option2);
                    questionSimple.setQuestionSimpleOptionDTOS(options);
                }
                swipMyAnswer(questionSimple, isShowRight);
            }
        }
        this.total = now - 1;
        if (spotsDialog2 != null) {
            spotsDialog2.cancel();
        }
    }

    /**
     * 包装查看解析
     *
     * @param questionParents
     */
    public void encodeCheck(List<QuestionParent> questionParents) {
        if (questionParents == null) {
            if (spotsDialog2 != null) {
                spotsDialog2.cancel();
            }
            return;
        }

        int now = 1;
        for (int i = 0; i < questionParents.size(); i++) {
            QuestionParent questionParent = questionParents.get(i);
            //跳过过渡页
            if (questionParent.isSpcePage()) {
                continue;
            }

            if (questionParent.getIsMaterial() == 1) {
                //材料题,编号
                for (QuestionSimple questionSimple : questionParent.getQuestionSimpleDTOS()) {
                    questionSimple.setParentPos(i);
                    questionSimple.setNum(now);
                    now++;
                    questionSimple.setShowRight(true);
                }
            } else {
                QuestionSimple questionSimple = questionParent.getQuestionSimpleDTOS().get(0);
                questionSimple.setParentPos(i);
                questionSimple.setNum(now);
                now++;
                questionSimple.setShowRight(true);

            }
        }
        this.total = now - 1;
        if (spotsDialog2 != null) {
            spotsDialog2.cancel();
        }
    }

    public ArrayList<QuestionParent> getQuestiongWrongs(List<QuestionParent> questionParents) {
        ArrayList<QuestionParent> arrayList = new ArrayList<>();
        for (QuestionParent questionParent : questionParents) {
            if (questionParent.isSpcePage()) {
                continue;
            }
            for (QuestionSimple questionSimple : questionParent.getQuestionSimpleDTOS()) {
                if (questionSimple.getIsAnswerRight() == 0) {
                    arrayList.add(questionParent);
                }
            }
        }
        return arrayList;
    }

//    public UserAnswerPager getUserAnswerPager(List<QuestionParent> questionParents, int pagerId) {
//        if (questionParents == null) {
//            return null;
//        }
//        UserAnswerPager userAnswerPager = new UserAnswerPager();
//        userAnswerPager.setData(new ArrayList<>());
//        userAnswerPager.setMemberTestPaperId(pagerId);
//        for (QuestionParent questionParent : questionParents) {
//            if (questionParent.isSpcePage()) {
//                continue;
//            }
//            for (QuestionSimple questionSimple : questionParent.getQuestionSimpleDTOS()) {
//                if (
//                        questionSimple.getIsAnswerRight() == 2
//                                || questionSimple.getMyChooseAnswer() == null
//                                || questionSimple.getMyChooseAnswer().size() == 0) {
//                    //跳过未作答的
//                    continue;
//                }
//                UserAnswer userAnswer = new UserAnswer();
//                userAnswer.setMemberPaperDetailId(questionSimple.getMemberPaperDetailId());
//                userAnswer.setSeconds(questionSimple.getUseTime() / 1000);
//                if (questionSimple.getQuestionType() == 1 ||
//                        questionSimple.getQuestionType() == 2
//                ) {
//                    //选择
//                    if (!questionSimple.getMyChooseAnswer().contains("?")) {
//                        userAnswerPager.setTime(userAnswerPager.getTime() + questionSimple.getUseTime() / 1000);
//                        userAnswer.setAnswer(questionSimple.getMyChooseAnswer());
//                        userAnswerPager.getData().add(userAnswer);
//                    } else {
//                        userAnswerPager.setTime(userAnswerPager.getTime() + questionSimple.getUseTime() / 1000);
//                        List<String> mAns = new ArrayList<>();
//                        mAns.add("NO");
//                        userAnswer.setAnswer(mAns);
//                        userAnswerPager.getData().add(userAnswer);
//                    }
//                } else if (questionSimple.getQuestionType() == 3) {
//                    //判断
//                    List<String> myAnswerUp = new ArrayList<>();
//                    for (String myAnswer : questionSimple.getMyChooseAnswer()) {
//                        if (myAnswer.equals("A")) {
//                            myAnswerUp.add("1");
//                        } else if (myAnswer.equals("B")) {
//                            myAnswerUp.add("2");
//                        } else if (myAnswer.equals("?")) {
//                            myAnswerUp.add("NO");
//                        }
//                    }
//                    userAnswerPager.setTime(userAnswerPager.getTime() + questionSimple.getUseTime() / 1000);
//                    userAnswer.setAnswer(myAnswerUp);
//                    userAnswerPager.getData().add(userAnswer);
//
//                }
//            }
//        }
//
//        if (userAnswerPager.getData() == null || userAnswerPager.getData().size() == 0) {
//            return null;
//        }
//        return userAnswerPager;
//    }


    public void showAnswerCard() {
    }

    @Override
    public void onBackPressed() {
        if (layPaintControll.getVisibility() == View.VISIBLE || paintView.getVisibility() == View.VISIBLE) {
            layPaintControll.setVisibility(View.GONE);
            paintView.setVisibility(View.GONE);
        } else {
            super.onBackPressed();
        }
    }

    private void swipMyAnswer(QuestionSimple questionSimple, boolean isShowAsy) {
        if (!TextUtils.isEmpty(questionSimple.getAnswer())) {
            ArrayList<String> strings = new ArrayList<>();
            String[] ss = questionSimple.getAnswer().split(",");
            for (String si : ss) {
                strings.add(si);
            }
            questionSimple.setMyChooseAnswer(strings);
            if (questionSimple.getQuestionType() == 3) {
                questionSimple.setIsAnswerRight(
                        questionSimple.getAnswer().equals("1")
                                && questionSimple.getRightKey().equals("A")
                                ||
                                questionSimple.getAnswer().equals("2")
                                        && questionSimple.getRightKey().equals("B")
                                ? 1 : 0);
            } else {
                questionSimple.setIsAnswerRight(
                        questionSimple.getRightKey().equals(questionSimple.getAnswer()) ? 1 : 0
                );
            }
            if (isShowAsy) {
                questionSimple.setShowRight(true);
            }
        }
    }

    protected QuestionSimple getLastDonePos() {
        if (questionParents != null) {
            QuestionSimple questionSimpleLastOne = null;
            for (int i = questionParents.size() - 1; i >= 0; i--) {
                QuestionParent questionParent = questionParents.get(i);
                if (questionParent.isSpcePage()) {
                    continue;
                }
                if (questionParent.getQuestionSimpleDTOS() != null)
                    for (QuestionSimple questionSimple : questionParent.getQuestionSimpleDTOS()) {
                        if (questionSimple.getMyChooseAnswer() != null) {
                            if (questionSimpleLastOne == null) {
                                return questionSimple;
                            } else {
                                return questionSimpleLastOne;
                            }
                        }
                        questionSimpleLastOne = questionSimple;
                    }
            }
        }
        return null;
    }

    /**
     * 到指定位置
     *
     * @param questionSimple
     */
    protected void goDesPosition(QuestionSimple questionSimple) {
        int parentPosition = questionSimple.getParentPos();
        viewPager.setCurrentItem(parentPosition);
        QuestionParent questionParent = questionParents.get(parentPosition);
        if (questionParent.getIsMaterial() == 1) {
            int childPosition = questionParent.getQuestionSimpleDTOS().indexOf(questionSimple);
            BaseMateriFragment questionMateriExaminationFragment
                    = (BaseMateriFragment) questionFragmentAdapter.getCurrentFragment();
            questionMateriExaminationFragment.goIndex(childPosition);
        }
    }

    void changeTextSize() {
//        questionFragmentAdapter.notifyDataSetChanged();
        BaseMvpFragment fragment = questionFragmentAdapter.getCurrentFragment();
        if (fragment instanceof BaseMateriFragment) {
            ((BaseMateriFragment) fragment).resetTextSize();
        } else if (fragment instanceof BaseSimpleFragment) {
            ((BaseSimpleFragment) fragment).resetTextSize();
        }

    }

    void resetTextSize() {
        //重设adapter试试
        QuestionSimple indexNow = currentSimple;
        questionFragmentAdapter = new BaseMateriAdapter<T, K>(getSupportFragmentManager(),
                questionParents, total, getClassT(), getClassK());
        viewPager.setAdapter(questionFragmentAdapter);
        goDesPosition(indexNow);
    }

    @Override
    public void onError(NetErrorException throwable) {
        super.onError(throwable);
        if (spotsDialog2 != null) {
            spotsDialog2.cancel();
        }
    }
}


